﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.Menus;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Transactions;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.Menus
{
    public class AddRoleMenuComamndHandler : IRequestHandler<AddRoleMenuComamnd, APIResult<object>>
    {
        private readonly IBaseRepository<RoleMenu> rolemenuRep;
        private readonly IMapper mapper;
        private readonly IBaseRepository<Role> roleRep;
        private readonly IBaseRepository<Menu> menuRep;

        public AddRoleMenuComamndHandler(IBaseRepository<RoleMenu> rolemenuRep,IMapper mapper,IBaseRepository<Role> roleRep,IBaseRepository<Menu> menuRep)
        {
            this.rolemenuRep = rolemenuRep;
            this.mapper = mapper;
            this.roleRep = roleRep;
            this.menuRep = menuRep;
        }

        public async Task<APIResult<object>> Handle(AddRoleMenuComamnd request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);

            try
            {
                // 验证角色存在（单个角色）
                var roleExists = await roleRep.GetAll().Result
                    .AnyAsync(r => r.RoleId == request.roleId);

                if (!roleExists)
                {
                    result.Code = APIEnum.操作失败;
                    result.Msg = "角色不存在";
                    return result;
                }

                // 验证菜单存在（多个菜单）
                var existingMenus = await menuRep.GetAll().Result
                    .Where(m => request.MenuId.Contains(m.MenuId))
                    .CountAsync();

                if (existingMenus != request.MenuId.Count)
                {
                    result.Code = APIEnum.操作失败;
                    result.Msg = "部分菜单不存在";
                    return result;
                }

                // 获取现有关系
                var existingRelations = await rolemenuRep.GetAll().Result
                    .Where(rm => rm.RoleId == request.roleId
                           && request.MenuId.Contains(rm.MenuId))
                    .ToListAsync();

                // 生成需要添加的关系
                var newRelations = request.MenuId
                    .Where(menuId =>
                        !existingRelations.Any(er => er.MenuId == menuId))
                    .Select(menuId => new RoleMenu
                    {
                        RoleId = request.roleId,
                        MenuId = menuId,
                       
                    })
                    .ToList();

                // 批量添加
                if (newRelations.Count > 0)
                {
                    var affected = await rolemenuRep.AddRanges(newRelations);
                    result.data = affected;
                }

                scope.Complete();

                result.Code = APIEnum.操作成功;
                result.Msg = $"成功添加{newRelations.Count}条权限记录";
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.操作失败;
                result.Msg = $"操作失败：{ex.Message}";
            }

            return result;
        }
    }
    }

